package com.imageim.yimirror.ui.fragment;

import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.imageim.yimirror.R;
import com.imageim.yimirror.base.BaseFragment;
import com.imageim.yimirror.base.Constants;
import com.imageim.yimirror.bean.IntelligenRecommendBean;
import com.imageim.yimirror.common.event.EventCode;
import com.imageim.yimirror.common.event.EventMessage;
import com.imageim.yimirror.common.network.constants.NetConstants;
import com.imageim.yimirror.common.ui.GlideUtils;
import com.imageim.yimirror.common.util.AnimUtil;
import com.imageim.yimirror.common.util.ClickUtil;
import com.imageim.yimirror.common.util.UserUtil;
import com.imageim.yimirror.net.NetPresenterImpl;
import com.imageim.yimirror.net.NetView;
import com.imageim.yimirror.ui.adapter.MyCollectPhotoAdapter;
import com.imageim.yimirror.ui.widght.EmptyView;
import com.imageim.yimirror.ui.widght.LoadingView;
import com.makeramen.roundedimageview.RoundedImageView;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Yuaihen.
 * on 2018/12/4
 * 我的喜欢Fragment  收藏的服装数据
 */
public class MyCollectFragment extends BaseFragment implements NetView, OnRefreshListener, MyCollectPhotoAdapter.OnItemClickListener {

    @BindView(R.id.rv_photo)
    RecyclerView mRvPhoto;
    @BindView(R.id.iv_main_photo)
    RoundedImageView mIvMainPhoto;
    @BindView(R.id.tv_match)
    TextView mTvMatch;
    @BindView(R.id.iv_match1)
    ImageView mIvMatch1;
    @BindView(R.id.iv_match2)
    ImageView mIvMatch2;
    @BindView(R.id.iv_match3)
    ImageView mIvMatch3;
    @BindView(R.id.ll_match)
    LinearLayout mLlMatch;
    @BindView(R.id.tv_like)
    TextView mTvLike;
    @BindView(R.id.loading_view)
    LoadingView mLoadingView;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout mSmartRefresh;
    @BindView(R.id.tv_suit_occasion)
    TextView mTvSuitOccasion;
    @BindView(R.id.empty_view)
    EmptyView mEmptyView;
    private MyCollectPhotoAdapter mMyCollectPhotoAdapter;
    private List<IntelligenRecommendBean.ClothingsBean> mClothingsList;
    private float mDensity;
    private int mHiddenViewMeasuredHeight;
    private NetPresenterImpl mNetPresenter;
    private HashMap<String, String> map;
    private int currentItemPosition = 0;
    private int currentOccasionId = 0;
    private int currentColorId = 0;
    private boolean isRefresh;
    private ImageView[] mIvMatchViews;
    private List<IntelligenRecommendBean.ClothingsBean.accessoryListBean> mAccessoryList;
    private HashMap<String, String> mCancelCollectMap;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my_collect;
    }

    @Override
    protected void initListener() {
        mIvMatchViews = new ImageView[]{mIvMatch1, mIvMatch2, mIvMatch3};

        //搭配区域布局的高度 700dp
        mDensity = getResources().getDisplayMetrics().density;
        mHiddenViewMeasuredHeight = (int) (mDensity * 700 + 0.5);

        mRvPhoto.setLayoutManager(new LinearLayoutManager(mContext));
        mMyCollectPhotoAdapter = new MyCollectPhotoAdapter(mContext, mClothingsList);
        mRvPhoto.setAdapter(mMyCollectPhotoAdapter);
        mMyCollectPhotoAdapter.setOnItemClickListener(this);

        //下拉刷新
        mSmartRefresh.setRefreshHeader(new MaterialHeader(mContext));
        mSmartRefresh.setOnRefreshListener(this);

        mEmptyView.setOnFinishBtnClickListener(() -> getClothingResult(currentOccasionId, currentColorId));
    }

    @Override
    protected void initData() {
        mNetPresenter = new NetPresenterImpl(this);
        getClothingResult(currentOccasionId, currentColorId);
    }


    private static final int MSG_GET_CLOTHING = 0x001;
    private static final int MSG_CANCEL_COLLECT = 0x004;

    /**
     * 获取收藏的服装信息
     *
     * @param occasionId 场合ID    只能查询单个场合ID
     * @param colorId    colorId   只能查询单个ColorID
     */
    private void getClothingResult(final int occasionId, final int colorId) {
        currentItemPosition = 0;
        currentOccasionId = occasionId;
        currentColorId = colorId;

        if (map == null) {
            map = new HashMap<>(8);
        }
        map.put(Constants.PHOTO_NO, UserUtil.getPhotoNo());
        map.put(Constants.OCCASIONIDS, currentOccasionId + "");
        map.put(Constants.COLOR_LABEL_IDS, currentColorId + "");

        //temp
        //        map.put(Constants.PHOTO_NO, "CN201812042048016FYT");
        //        map.put("mac", "AC83F3B47D82");
        //        map.put("token", "2d559331d31044ea81b19da9bc42078c1544099515778");
        //        map.put(Constants.OCCASIONIDS, currentOccasionId + "");
        //        map.put(Constants.COLOR_LABEL_IDS, currentColorId + "");
        mNetPresenter.getObject(mContext, NetConstants.URL.QUERY_MY_COLLECT, map, IntelligenRecommendBean.class, MSG_GET_CLOTHING);
    }


    /**
     * 取消收藏
     */
    private void cancelCollect(int position) {
        if (mClothingsList == null || mClothingsList.size() <= 0) {
            return;
        }

        //  0未收藏   1收藏
        int collectFlag = mClothingsList.get(position).getCollectFlag();
        String clothingCode = mClothingsList.get(position).getClothingCode();
        if (!TextUtils.isEmpty(clothingCode)) {
            if (collectFlag == 1) {
                //已经收藏  取消收藏
                cancelCollect(clothingCode);
            } else {
                toast("该衣服未收藏哦~");
            }
        }

    }

    private String deleteClothCode;

    /**
     * 上传取消收藏的服装编码到服务器
     *
     * @param clothingCode 服装编码
     */
    private void cancelCollect(String clothingCode) {
        deleteClothCode = clothingCode;

        if (mCancelCollectMap == null) {
            mCancelCollectMap = new HashMap<>(4);
        }
        mCancelCollectMap.put(Constants.USER_ID, UserUtil.getUserId());
        mCancelCollectMap.put(Constants.CLOTHING_CODE, clothingCode);

        //temp
        //        mCancelCollectMap.put(Constants.PHOTO_NO, "CN201812042048016FYT");
        //        mCancelCollectMap.put("mac", "AC83F3B47D82");
        //        mCancelCollectMap.put("token", "2d559331d31044ea81b19da9bc42078c1544099515778");
        //        mCancelCollectMap.put("userId", "BC20181206171718ibsQ");
        mNetPresenter.getObject(mContext, NetConstants.URL.CANCEL_COLLECT, mCancelCollectMap, MSG_CANCEL_COLLECT);
    }


    /**
     * 设置主图以及配饰信息
     *
     * @param position item的位置
     */
    private void setMainAndMatchData(int position) {
        if (mClothingsList == null || mClothingsList.size() <= 0) {
            return;
        }

        //切换小图时关闭搭配区域
        if (mLlMatch.getVisibility() == View.VISIBLE) {
            closeMatchArea();
        }

        //设置数据
        IntelligenRecommendBean.ClothingsBean clothingsBean = mClothingsList.get(position);
        if (clothingsBean != null) {
            String clothingUrl = clothingsBean.getClothingUrl();
            if (!TextUtils.isEmpty(clothingUrl)) {
                GlideUtils.display(mIvMainPhoto, clothingUrl);
            }

            //是否收藏过 0未收藏 1收藏
            int collectFlag = clothingsBean.getCollectFlag();
            if (collectFlag == 1) {
                mTvLike.setSelected(true);
                mTvLike.setText("取消");
            } else {
                mTvLike.setSelected(false);
                mTvLike.setText("喜欢");
            }

            //搭配信息
            mAccessoryList = Optional.ofNullable(clothingsBean.getAccessoryList())
                    .orElse(new ArrayList<>());
            if (mAccessoryList.size() > 0) {
                mTvMatch.setVisibility(View.VISIBLE);
                for (int i = 0; i < mAccessoryList.size(); i++) {
                    if (i >= mIvMatchViews.length) {
                        return;
                    }
                    String matchUrl = mAccessoryList.get(i).getClothingUrl();
                    if (!TextUtils.isEmpty(matchUrl)) {
                        GlideUtils.display(mIvMatchViews[i], matchUrl);
                    }
                }
            } else {
                mTvMatch.setVisibility(View.GONE);
            }


            //设置适用场合
            String occasionNames = clothingsBean.getOccasionNames();
            if (!TextUtils.isEmpty(occasionNames)) {
                mTvSuitOccasion.setVisibility(View.VISIBLE);
                String[] suitOccasionNames = occasionNames.split(",");
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < suitOccasionNames.length; i++) {
                    stringBuilder.append(suitOccasionNames[i]);
                    if (i != suitOccasionNames.length - 1) {
                        stringBuilder.append("、");
                    }
                }
                mTvSuitOccasion.setText(MessageFormat.format("适合场合：{0}", stringBuilder.toString()));
            } else {
                mTvSuitOccasion.setVisibility(View.GONE);
            }

        }
    }


    /**
     * 左侧Rv item点击重新设置主图和配饰
     */
    @Override
    public void onClickPhoto(int position) {
        if (currentItemPosition != position) {
            currentItemPosition = position;
            setMainAndMatchData(currentItemPosition);
        }
    }


    @OnClick({R.id.tv_match, R.id.tv_like})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.tv_match:
                //展开搭配区域
                if (mLlMatch.getVisibility() == View.GONE) {
                    openMatchArea();
                } else {
                    closeMatchArea();
                }
                break;
            case R.id.tv_like:
                //取消收藏
                if (ClickUtil.isValidClick()) {
                    cancelCollect(currentItemPosition);
                }
                break;
            default:
                break;
        }
    }


    /**
     * 从上往下滑动显示搭配区域
     * 如果没有配饰不操作
     */
    private void openMatchArea() {
        if (mAccessoryList != null && mAccessoryList.size() > 0) {
            mTvMatch.setSelected(true);
            AnimUtil.slideShowArea(mLlMatch, mHiddenViewMeasuredHeight, 500);
        }
    }

    /**
     * 从下往上滑动隐藏搭配区域
     * 如果没有配饰不操作
     */
    private void closeMatchArea() {
        if (mAccessoryList != null && mAccessoryList.size() > 0) {
            mTvMatch.setSelected(false);
            AnimUtil.slideHideArea(mLlMatch, mTvMatch, 500);
        }
    }


    @Override
    public void onLoadPre(int msgCode) {
        showLoading();
    }

    @Override
    public void onLoadSuccess(Object result, int msgCode) {
        hideLoading();
        if (msgCode == MSG_GET_CLOTHING) {
            hideEmptyView();
            if (isRefresh) {
                mSmartRefresh.finishRefresh();
                isRefresh = false;
            }
            setData(result);
        } else if (msgCode == MSG_CANCEL_COLLECT) {
            updateAdapter();
        }
    }

    /**
     * 从Adapter中删除对应收藏的服装
     * 刷新收藏列表并通知为您推荐和智能推荐界面刷新
     */
    private void updateAdapter() {
        EventBus.getDefault().post(new EventMessage(EventCode.CODE_REFRESH_ADAPTER, deleteClothCode));

        if (mClothingsList == null || mClothingsList.size() <= 0) {
            return;
        }

        //删除完成 重置currentItemPosition = 0
        mClothingsList.remove(currentItemPosition);
        currentItemPosition = 0;
        if (mClothingsList.size() > 0) {
            mMyCollectPhotoAdapter.update(mClothingsList);
            setMainAndMatchData(currentItemPosition);
            mRvPhoto.scrollToPosition(0);
        } else {
            showEmptyView(false);
            mMyCollectPhotoAdapter.update(mClothingsList);
            mIvMainPhoto.setImageResource(R.drawable.ic_no_main_photo);
            hideLikeAndMatchArea();
        }
    }

    @Override
    public void onLoadFail(int errorCode, String errorMsg, int msgCode) {
        hideLoading();
        if (msgCode == MSG_GET_CLOTHING) {
            if (isRefresh) {
                mSmartRefresh.finishRefresh();
                isRefresh = false;
            }
            showEmptyView(true);
        }
        toast(errorCode + errorMsg);
    }


    /**
     * 设置Adapter 场合颜色和配饰信息
     *
     * @param result 返回的bean
     */
    private void setData(Object result) {
        IntelligenRecommendBean bean = (IntelligenRecommendBean) result;

        //服装信息
        mClothingsList = Optional.ofNullable(bean)
                .flatMap(b -> Optional.ofNullable(b.getClothings()))
                .orElse(new ArrayList<>());

        setAdapter();
    }


    /**
     * 设置服装Adapter
     */
    private void setAdapter() {
        if (mClothingsList.size() > 0) {
            showLikeAndMatchArea();
            mClothingsList.get(0).setChecked(true);
            mMyCollectPhotoAdapter.update(mClothingsList);
            if (mRvPhoto != null && mRvPhoto.getChildCount() > 0) {
                mRvPhoto.scrollToPosition(0);
            }
            setMainAndMatchData(0);
        } else {
            showEmptyView(false);
            mMyCollectPhotoAdapter.update(mClothingsList);
            mIvMainPhoto.setImageResource(R.drawable.ic_no_main_photo);
            hideLikeAndMatchArea();
        }
    }


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        if (mNetPresenter != null) {
            isRefresh = true;
            getClothingResult(currentOccasionId, currentColorId);
        }
    }


    private void showLoading() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.VISIBLE);
        }
    }

    private void hideLoading() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
        }
    }


    /**
     * 显示空布局
     *
     * @param isError 是网络错误还是数据为空
     */
    private void showEmptyView(boolean isError) {
        if (mEmptyView != null) {
            mEmptyView.setVisibility(View.VISIBLE);
            //网络错误显示刷新按钮
            if (isError) {
                mEmptyView.setErrorImg(R.drawable.ic_error);
                mEmptyView.setErrorContent("数据获取失败，请重试~");
                mEmptyView.setBtnVisiable(true);
            } else {
                mEmptyView.setErrorImg(R.drawable.ic_no_result);
                mEmptyView.setErrorContent("暂无服装数据~");
                mEmptyView.setBtnVisiable(false);
            }
        }
    }

    private void hideEmptyView() {
        if (mEmptyView != null) {
            if (mEmptyView.getVisibility() == View.VISIBLE) {
                mEmptyView.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 显示收藏和搭配区域
     */
    private void showLikeAndMatchArea() {
        mTvLike.setVisibility(View.VISIBLE);
        mTvMatch.setVisibility(View.VISIBLE);
    }

    private void hideLikeAndMatchArea() {
        mTvLike.setVisibility(View.GONE);
        mTvMatch.setVisibility(View.GONE);
    }


    @Override
    public void onEventMainThread(EventMessage event) {
        super.onEventMainThread(event);
        if (event.getCode() == EventCode.CODE_REFRESH_WITH_COLLECT_PAGE) {
            getClothingResult(currentOccasionId, currentColorId);
        }
    }


}
